/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cfparam_fuzzer.h"

#include <securec.h>

#include "cf_param.h"
#include "cf_memory.h"
#include "cf_result.h"

namespace OHOS {

    bool CfParamAddandGetFuzzTest(const uint8_t* data, size_t size)
    {
        CfParamSet *paramSet = nullptr;

        int32_t ret = CfInitParamSet(&paramSet);
        if (ret != CF_SUCCESS) {
            return false;
        }
        if (data == nullptr || size < (sizeof(uint32_t) + 1)) {
            return false;
        }
        uint32_t offset = 0;
        CfParam params[1] = {};
        size_t i = 0;
        params[0].tag = *reinterpret_cast<const uint32_t *>(data + offset);
        offset += sizeof(uint32_t);

        params[i].blob.size = size - offset;

        params[i].blob.data = const_cast<uint8_t *>(data + offset);

        (void)CfAddParams(paramSet, params, 1);

        CfParam *paramsGet = nullptr;
        CfGetParam(paramSet, params[0].tag, &paramsGet);
        CfFreeParamSet(&paramSet);

        return true;
    }

    bool CfBuildParamSetFuzzTest(const uint8_t* data, size_t size)
    {
        CfParamSet *paramSet = nullptr;
        int32_t ret = CfInitParamSet(&paramSet);
        if (ret != CF_SUCCESS) {
            return false;
        }
        paramSet->paramsCnt = 1;
        paramSet->paramSetSize += sizeof(CfParam) + size + 1; /* invalid size */
        paramSet->params[0].tag = CF_TAG_PARAM0_BUFFER;
        paramSet->params[0].blob.size = size;
        paramSet->params[0].blob.data = const_cast<uint8_t *>(data);

        (void)CfBuildParamSet(&paramSet);

        CfFreeParamSet(&paramSet);
        return true;
    }
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
    /* Run your code on data */
    OHOS::CfParamAddandGetFuzzTest(data, size);
    OHOS::CfBuildParamSetFuzzTest(data, size);
    return 0;
}
